const fs = require('fs').promises;
const path = require('path');

const logsDir = path.join(__dirname, '../../database/logs');

// 确保日志目录存在
async function ensureLogsDir() {
  try {
    await fs.access(logsDir);
  } catch (error) {
    if (error.code === 'ENOENT') {
      await fs.mkdir(logsDir, { recursive: true });
    } else {
      throw error;
    }
  }
}

// 获取所有日志记录
async function getAllLogs(page = 1, limit = 10) {
  await ensureLogsDir();
  
  try {
    const files = await fs.readdir(logsDir);
    const logFiles = files.filter(file => file.endsWith('.json'));
    
    // 读取所有日志文件
    const logs = await Promise.all(
      logFiles.map(async (file) => {
        const data = await fs.readFile(path.join(logsDir, file), 'utf8');
        return JSON.parse(data);
      })
    );
    
    // 按运行时间降序排序
    logs.sort((a, b) => new Date(b.runTime) - new Date(a.runTime));
    
    // 分页处理
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const paginatedLogs = logs.slice(startIndex, endIndex);
    
    return {
      total: logs.length,
      page,
      limit,
      data: paginatedLogs
    };
  } catch (error) {
    if (error.code === 'ENOENT') {
      return {
        total: 0,
        page,
        limit,
        data: []
      };
    }
    throw error;
  }
}

// 获取特定事件的日志记录
async function getLogsByEventId(eventId, page = 1, limit = 10) {
  await ensureLogsDir();
  
  try {
    const files = await fs.readdir(logsDir);
    const logFiles = files.filter(file => file.endsWith('.json'));
    
    // 读取所有日志文件
    const allLogs = await Promise.all(
      logFiles.map(async (file) => {
        const data = await fs.readFile(path.join(logsDir, file), 'utf8');
        return JSON.parse(data);
      })
    );
    
    // 过滤特定事件的日志
    const logs = allLogs.filter(log => log.eventId === eventId);
    
    // 按运行时间降序排序
    logs.sort((a, b) => new Date(b.runTime) - new Date(a.runTime));
    
    // 分页处理
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const paginatedLogs = logs.slice(startIndex, endIndex);
    
    return {
      total: logs.length,
      page,
      limit,
      data: paginatedLogs
    };
  } catch (error) {
    if (error.code === 'ENOENT') {
      return {
        total: 0,
        page,
        limit,
        data: []
      };
    }
    throw error;
  }
}

// 获取单个日志记录
async function getLogById(id) {
  await ensureLogsDir();
  
  try {
    const filePath = path.join(logsDir, `${id}.json`);
    const data = await fs.readFile(filePath, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    if (error.code === 'ENOENT') {
      return null;
    }
    throw error;
  }
}

// 创建日志记录
async function createLog(logData) {
  await ensureLogsDir();
  
  try {
    // 确保有ID和时间戳
    if (!logData.id) {
      logData.id = `log_${Date.now()}`;
    }
    
    if (!logData.runTime) {
      logData.runTime = new Date().toISOString();
    }
    
    const filePath = path.join(logsDir, `${logData.id}.json`);
    await fs.writeFile(filePath, JSON.stringify(logData, null, 2), 'utf8');
    return logData;
  } catch (error) {
    throw error;
  }
}

// 删除日志记录
async function deleteLog(id) {
  await ensureLogsDir();
  
  try {
    const filePath = path.join(logsDir, `${id}.json`);
    await fs.unlink(filePath);
    return true;
  } catch (error) {
    if (error.code === 'ENOENT') {
      return false;
    }
    throw error;
  }
}

// 清空特定事件的所有日志
async function clearEventLogs(eventId) {
  await ensureLogsDir();
  
  try {
    const files = await fs.readdir(logsDir);
    const logFiles = files.filter(file => file.endsWith('.json'));
    
    // 读取所有日志文件
    for (const file of logFiles) {
      const filePath = path.join(logsDir, file);
      const data = await fs.readFile(filePath, 'utf8');
      const log = JSON.parse(data);
      
      if (log.eventId === eventId) {
        await fs.unlink(filePath);
      }
    }
    
    return true;
  } catch (error) {
    throw error;
  }
}

module.exports = {
  getAllLogs,
  getLogsByEventId,
  getLogById,
  createLog,
  deleteLog,
  clearEventLogs
}; 